package org.cms;

import org.cms.entities.Attendee;
import org.cms.entities.AttendeeId;
import org.cms.entities.Event;
import org.cms.raw.calendar.AttendeeRaw;
import org.cms.raw.calendar.EventRaw;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by elnoa on 29/10/14.
 */
public class EventMapper {

    private static final String DATEFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; //2014-10-22T14:24:41.754Z
    private static final String STARTENDFORMAT = "yyyy-MM-dd'T'HH:mm:ssX";//2014-10-22T11:15:00+02:00


    public static Event map(EventRaw eventRaw) {
        Event event = new Event();
        event.setId(eventRaw.getId());
        event.setCreated(getTimeStamp(eventRaw.getCreated(), DATEFORMAT));
        event.setLastUpdate(getTimeStamp(eventRaw.getUpdated(), DATEFORMAT));

        event.setStart(getTimeStamp(eventRaw.getStart().getDateTime(), STARTENDFORMAT));
        event.setEnd(getTimeStamp(eventRaw.getEnd().getDateTime(), STARTENDFORMAT));

        event.setLocation(eventRaw.getLocation());
        event.setSummary(eventRaw.getSummary());
        event.setStatus(eventRaw.getStatus());
        event.setAttendee(attendeeMapper(eventRaw.getAttendees()));
        
        return event;
    }

    private static List<Attendee> attendeeMapper(AttendeeRaw[] attendees) {
        List<Attendee> attendeeList = new ArrayList<>();
        if (attendees != null && attendees.length > 0) {
            for (AttendeeRaw attendeeRaw : attendees) {
                Attendee attendee = new Attendee();
                String displayName = attendeeRaw.getDisplayName() == null ? "UNDEFINED" : attendeeRaw.getDisplayName();
                attendee.setId(new AttendeeId(displayName,attendeeRaw.getEmail()));
                attendee.setOptional(attendeeRaw.isOptional());
                attendee.setOrganizer(attendeeRaw.isOrganizer());
                attendee.setAdditionalGuests(attendeeRaw.getAdditionalGuests());
                attendee.setResponseStatus(attendeeRaw.getResponseStatus());

                attendeeList.add(attendee);
            }
        }
        return attendeeList;
    }

    public static Timestamp getTimeStamp(String timestamp, String dateformat) {

        //no date is set
        if (timestamp == null) {
            return null;
        }
        Timestamp ts = null;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);
            Date parsedDate = dateFormat.parse(timestamp);
            ts = new java.sql.Timestamp(parsedDate.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ts;
    }
}
